package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type CouponReturn struct {
	ID              int                    `gorm:"type:int(11); primaryKey" json:"id"`
	Aid             int                    `gorm:"type:int(11);" json:"aid"`                  //商户id
	Type            int                    `gorm:"type:int(11);" json:"type"`                 //1代金券
	Name            string                 `gorm:"type:varchar(255);"json:"name"`             //优惠券名称
	Starttime       int                    `gorm:"type:int(11);" json:"starttime"`            //开始时间
	Endtime         int                    `gorm:"type:int(11);" json:"endtime"`              //结束时间
	Yxqtype         int                    `gorm:"type:int(11);" json:"yxqtype"`              //有效期类型 1定时间范围 2领取后时长
	Yxqdate         int                    `gorm:"type:int(11);" json:"yxqdate"`              //领取后多少天有效
	YxqstartTime    int                    `gorm:"type:int(11);" json:"yxqstart_time"`        //有效期时间开始时间
	YxqendTime      int                    `gorm:"type:int(11);" json:"yxqend_time"`          //有效期时间结束时间
	Money           decimal.Decimal        `json:"money"`                                     //抵扣金额
	Minprice        decimal.Decimal        `json:"minprice"`                                  //最低消费金额
	Stock           int                    `gorm:"type:int(11);" json:"stock"`                //库存
	Perlimit        int                    `gorm:"type:int(11);" json:"perlimit"`             //每人可领数量
	Usetips         string                 `gorm:"type:varchar(255);"json:"usetips"`          //使用说明
	Price           decimal.Decimal        `json:"price"`                                     //所需金额
	Score           int                    `gorm:"type:int(11);" json:"score"`                //所需积分
	Createtime      int                    `gorm:"type:int(11);" json:"createtime"`           //
	Tolist          int                    `gorm:"type:int(11);" json:"tolist"`               //是否可直接领取 0:是 2:否
	Showtj          string                 `gorm:"type:varchar(255);"json:"showtj"`           //显示条件 -1不限制
	Usetj           string                 `gorm:"type:varchar(255);"json:"usetj"`            //使用条件 -1不限制
	Isgive          int                    `gorm:"type:int(11);" json:"isgive"`               //是否可赠送 0不可赠送 1可赠送
	Gettj           string                 `gorm:"type:varchar(255);"json:"gettj"`            //领取条件 -1不限制
	Fwtype          int                    `gorm:"type:int(11);" json:"fwtype"`               //0全场通用,1指定类目,2指定商品,3指定服务商品
	Categoryids     string                 `gorm:"type:varchar(255);"json:"categoryids"`      //指定类目ids
	Productids      string                 `gorm:"type:varchar(255);"json:"productids"`       //指定商品ids
	YuyueProductids string                 `gorm:"type:varchar(255);"json:"yuyue_productids"` //指定服务商品ids
	Status          int                    `gorm:"type:int(11);" json:"status"`               //状态
	CateList        []models.MShopCategory `json:"cate_list"`
	FuShop          []models.MFuProduct    `json:"fu_shop"`
}

// 获取优惠券
func CouponList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []CouponReturn
	var listCoupon []models.MCoupon
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MCoupon)).Where("aid=? AND name LIKE ?", jsonData.Aid, "%"+jsonData.Name+"%")
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&listCoupon)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	for _, v := range listCoupon {
		var one CouponReturn
		one.ID = v.ID
		one.Type = v.Type
		one.YxqendTime = v.YxqendTime
		one.Aid = v.Aid
		one.YxqstartTime = v.YxqstartTime
		one.YuyueProductids = v.YuyueProductids
		one.Productids = v.Productids
		one.Categoryids = v.Categoryids
		one.Fwtype = v.Fwtype
		one.Gettj = v.Gettj
		one.Isgive = v.Isgive
		one.Usetj = v.Usetj
		one.Showtj = v.Showtj
		one.Tolist = v.Tolist
		one.Score = v.Score
		one.Money = v.Money
		one.Minprice = v.Minprice
		one.Price = v.Price
		one.Perlimit = v.Perlimit
		one.Stock = v.Stock
		one.Starttime = v.Starttime
		one.Endtime = v.Endtime
		one.Yxqdate = v.Yxqdate
		one.Yxqtype = v.Yxqtype
		one.Name = v.Name
		one.Status = v.Status
		one.Createtime = v.Createtime
		one.Usetips = v.Usetips
		if v.Fwtype == 1 {
			//推荐分类
			var listTpro []models.MShopCategory
			if v.Categoryids != "" {
				var NewArr = strings.Split(v.Categoryids, ",")
				err = models.DB.Model(new(models.MShopCategory)).Where("id IN ?", NewArr).Find(&listTpro).Error
				if err != nil {
					define.Response.ResultFail(c, 10004, err.Error(), "")
					return
				}
			}
			one.CateList = listTpro
		} else if v.Fwtype == 2 {
			//推荐服务商品
			var listTpro []models.MFuProduct
			if v.Productids != "" {
				var NewArr = strings.Split(v.Productids, ",")
				err = models.DB.Model(new(models.MFuProduct)).Where("id IN ?", NewArr).Find(&listTpro).Error
				if err != nil {
					define.Response.ResultFail(c, 10004, err.Error(), "")
					return
				}
			}
			one.FuShop = listTpro
		}
		list = append(list, one)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 新增/修改优惠券
func CouponAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MCoupon
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"name":             jsonData.Name,
			"type":             jsonData.Type,
			"status":           jsonData.Status,
			"starttime":        jsonData.Starttime,
			"endtime":          jsonData.Endtime,
			"yxqtype":          jsonData.Yxqtype,
			"yxqdate":          jsonData.Yxqdate,
			"yxqstart_time":    jsonData.YxqstartTime / 1000,
			"yxqend_time":      jsonData.YxqendTime / 1000,
			"money":            jsonData.Money,
			"minprice":         jsonData.Minprice,
			"stock":            jsonData.Stock,
			"perlimit":         jsonData.Perlimit,
			"usetips":          jsonData.Usetips,
			"price":            jsonData.Price,
			"score":            jsonData.Score,
			"tolist":           jsonData.Tolist,
			"showtj":           jsonData.Showtj,
			"usetj":            jsonData.Usetj,
			"isgive":           jsonData.Isgive,
			"gettj":            jsonData.Gettj,
			"fwtype":           jsonData.Fwtype,
			"categoryids":      jsonData.Categoryids,
			"productids":       jsonData.Productids,
			"yuyue_productids": jsonData.YuyueProductids,
			"buyproids":        jsonData.Buyproids,
			"buyprogive":       jsonData.Buyprogive,
			"buypro_give_num":  jsonData.BuyproGiveNum,
		}
		err = models.DB.Model(new(models.MCoupon)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10003,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了优惠券:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改优惠券", userId, logData, bid, jsonData.Aid)
	} else {
		//生成邀请码
		CardNumber := time.Now().Format("20060102150405")
		inviteCode1 := CardNumber + string(define.Krand(16, define.KC_RAND_KIND_UPPER))
		var data models.MCoupon
		data.Name = jsonData.Name
		data.Starttime = jsonData.Starttime
		data.Status = jsonData.Status
		data.Aid = jsonData.Aid
		data.Endtime = jsonData.Endtime
		data.Yxqtype = jsonData.Yxqtype
		data.Yxqdate = jsonData.Yxqdate
		data.Type = jsonData.Type
		data.YxqstartTime = jsonData.YxqstartTime / 1000
		data.YxqendTime = jsonData.YxqendTime / 1000
		data.Money = jsonData.Money
		data.Minprice = jsonData.Minprice
		data.Stock = jsonData.Stock
		data.Perlimit = jsonData.Perlimit
		data.Usetips = jsonData.Usetips
		data.Price = jsonData.Price
		data.Score = jsonData.Score
		data.Tolist = jsonData.Tolist
		data.Showtj = jsonData.Showtj
		data.Usetj = jsonData.Usetj
		data.Isgive = jsonData.Isgive
		data.Gettj = jsonData.Gettj
		data.Fwtype = jsonData.Fwtype
		data.Categoryids = jsonData.Categoryids
		data.Productids = jsonData.Productids
		data.YuyueProductids = jsonData.YuyueProductids
		data.Buyproids = jsonData.Buyproids
		data.Buyprogive = jsonData.Buyprogive
		data.BuyproGiveNum = jsonData.BuyproGiveNum
		data.Code = inviteCode1
		data.Createtime = int(time.Now().Unix())
		err = models.DB.Model(new(models.MCoupon)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个优惠券:" + jsonData.Name
		models.LogAdd(2, "新增优惠券", userId, logData, bid, jsonData.Aid)
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除优惠券
func CouponDel(c *gin.Context) {
	var jsonData models.MCoupon
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MCoupon
	models.DB.Model(new(models.MCoupon)).Where("id=?", jsonData.ID).First(&data)
	tx := models.DB.Begin()

	//删除
	err = tx.Delete(&models.MCoupon{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()

	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个优惠券:" + data.Name
	models.LogAdd(4, "删除优惠券", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
